// chat.js
const app = getApp();
const API_KEY = 'lKuvxeNclUEmiVo5OU3gGAvj';
const SECRET_KEY = 'rg14Z4kS7LKsJ04PSYoYzF4FGpnDGA32';

Page({
  data: {
    messages: [],
    inputValue: '',
    accessToken: ''
  },

  onLoad() {
    this.getToken();
  },

  getToken() {
    const url_token = `https://aip.baidubce.com/oauth/2.0/token?client_id=${API_KEY}&client_secret=${SECRET_KEY}&grant_type=client_credentials`;

    wx.request({
      url: url_token,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      success: res => {
        console.log(res);
        const accessToken = res.data.access_token;
        this.setData({ accessToken });
      },
      fail: err => {
        console.error('获取access_token失败', err);
      }
    });
  },

  onInput(e) {
    this.setData({
      inputValue: e.detail.value,
    });
  },

  sendMessage() {
    const { inputValue, messages, accessToken } = this.data;
    if (!inputValue.trim()) return;

    const userMessage = {
      role: 'user',
      content: inputValue,
    };

    this.setData({
      messages: [...messages, userMessage],
      inputValue: '',
    });

    this.getBotResponse(inputValue, accessToken);
  },

  getBotResponse(userInput, accessToken) {
    const url_chat = `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=${accessToken}`;

    const payload = {
      "messages": [
        {
          "role": "user",
          "content": userInput
        }
      ]
    };

    wx.request({
      url: url_chat,
      method: 'POST',
      data: payload,
      header: {
        'Content-Type': 'application/json'
      },
      success: res => {
        console.log(res);
        const botMessage = {
          role: 'bot',
          content: res.data.result,
        };

        this.setData({
          messages: [...this.data.messages, botMessage],
        });
      },
      fail: err => {
        console.error('获取机器人响应失败', err);
      }
    });
  },
});